﻿using System;
using System.Collections.Generic;
using System.Linq;
using SqlSugar;
using log4net.Core;
using Crossroad.Utils;
using Crossroad.Utils.Extensions;
using Crossroad.Core.Data;
using Crossroad.Core.Exceptions;
using Crossroad.Core.Helper;
using Crossroad.Core.Models;
using Crossroad.System.Widget.Model;
using Crossroad.System.User.Service.Impl;
using Crossroad.System.User.Service;

namespace Crossroad.System.Widget.Service.Impl
{
    /// <summary>
    /// 通知公告
    /// </summary>
    public class NoticeService: Access<Notice>, INoticeService
    {
        private readonly UserInfoService userInfoService;

        public NoticeService(
            IUserInfoService userInfoServiceIpt
        )
        {
            userInfoService = userInfoServiceIpt as UserInfoService;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="method"></param>
        /// <param name="loadRelevantData">是否加载关联数据</param>
        public Pagination<Notice> GetPaging(
            int pageIndex,
            int pageSize,
            Action<ISugarQueryable<Notice>> method,
			bool loadRelevantData = true
        )
        {
            var query =  db.Queryable<Notice>();
            method(query);
            var totalCount = 0;
            var page = new Pagination<Notice>
            {
                PageIndex = pageIndex,
                PageSize = pageSize,
            };
            page.Records = query.ToPageList(page.PageIndex, page.PageSize, ref totalCount);
            page.TotalCount = totalCount;
			if(loadRelevantData)
				Load(page.Records);

            return page;
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <param name="method"></param>
        /// <param name="loadRelevantData">是否加载关联数据</param>
        /// <returns></returns>
        public  List<Notice> GetList(
            Action<ISugarQueryable<Notice>> method,
			bool loadRelevantData = true
        )
        {
            var query =  db.Queryable<Notice>();
            method(query);
            var list = query.ToList();
			if(loadRelevantData)
				Load(list);

            return list;
        }

        /// <summary>
        /// 查询详情
        /// </summary>
        /// <param name="method"></param>
        /// <param name="loadRelevantData">是否加载关联数据</param>
        /// <returns></returns>
        public Notice GetEntity(
            Action<ISugarQueryable<Notice>> method,
			bool loadRelevantData = true
		)
        {
            var query =  db.Queryable<Notice>();
            method(query);
            Notice model = query.First();
            if (loadRelevantData)
                Load(model);

            return model;
        }

        /// <summary>
        /// 查询详情
        /// </summary>
        /// <param name="id"></param>
        /// <param name="loadRelevantData">是否加载关联数据</param>
        /// <returns></returns>
        public Notice GetEntity(int id, bool loadRelevantData = true)
        {
            Notice model = db.Queryable<Notice>().InSingle(id);
            if (loadRelevantData)
                Load(model);

            return model;
        }

        /// <summary>
        /// 根据id列表查询maps
        /// </summary>
        /// <param name="idList"></param>
        /// <returns></returns>
        public Dictionary<int, Notice> GetMaps(List<int> idList)
        {
            var maps = new Dictionary<int, Notice>();
            if (idList.Count < 1)
                return maps;

            var list = db.Queryable<Notice>()
                .In(f => f.id, idList.Distinct().ToArray())
                .ToList();

            list.ForEach(m =>
            {
                maps.Add(m.id, m);
            });

            return maps;
        }

        /// <summary>
        /// 新增返回详情
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public Notice CreateAt(Notice model)
        {
            model.createTime = DateTime.Now.ToTimeStamp();
            model = db.Insertable(model).ExecuteReturnEntity();

            return GetEntity(model.id);
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="model"></param>
		public Notice UpdateAt(Notice model) 
		{
			var rows = db.Updateable(model).IgnoreColumns(true).ExecuteCommand();

			return GetEntity(model.id);
		}

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="source"></param>
        public void DeleteAt(Notice source)
        {
             var rows = db.Deleteable<Notice>().In(source.id).ExecuteCommand();
            if (rows < 1)
                throw new LogicException("删除失败！");
        }


        #region 加载关联数据

        public void Load(List<Notice> list)
        {
            if (list.IsNull())
                return;

            var userIdList = new List<int>();
            list.ForEach(model =>
            {
                if (!model.creatorId.IsNull())
                    userIdList.Add(model.creatorId.Value);
            });
            var userMaps = userInfoService.GetMaps(userIdList);

            list.ForEach(model =>
            {
                if (!model.creatorId.IsNull() && userMaps.ContainsKey(model.creatorId.Value))
                    model.creatorName = userMaps[model.creatorId.Value].nickName;
            });
        }

        public void Load(Notice model)
        {
            if (model.IsNull())
                return;

            if (!model.creatorId.IsNull())
                model.creatorName = userInfoService.GetEntity(model.creatorId.Value, false)?.nickName;
        }

        #endregion


    }
}
